A local function is private to the .m file that contains it, and hence is only accessible from within the file. The following shows an example of local functions, contained in the file example.m:
% Defining two points, p1 and p2.
p1 = [3, 4]
p2 = [5, 6]
% Calling a local function.
d = distance(p1, p2)
% Defining a local function
function d = distance(p1, p2)
d = sqrt((p1(1) - p2(1))^2 + (p1(2) - p2(2))^2);
end
In the above code, distance is a local function, which can be called from the script above it in example.m. The local function distance only lives in example.m and is not accessible from elsewhere.
Running the script in example.m gives
p1 =
3.0000 4.0000
p2 =
5.0000 6.0000
d =
2.8284
Calling the local function distance from the console (which is the outside of example.m) fails:
p1 = [3, 4]
p2 = [4, 5]
distance(p1, p2)
p1 =
3.0000 4.0000
p2 =
4.0000 5.0000
Error at Line 1(1) of the Console. File named "distance.m" not found in Home.
Local functions can be defined after a list of statements in a script, or after a main function.
Local functions after a script can be defined with the following syntax:
% Script
statement_1
statement_2
...
statement_n
% Local function 1
function [out_11, ..., out_1n] = local1(in_11, ..., in_1m)
% Some statments
end
% Local function 2
function [out_21, ..., out_2n] = local2(in_21, ..., in_2m)
% Some statments
end
% More local functions...
% Local function k
function [out_k1, ..., out_kn] = localk(in_k1, ..., in_km)
% Some statments
end
Local functions after the main function can be defined with the following syntax:
% Main function
function [out_1, ..., out_n] = main(in_1, ..., in_m)
% Some statements
end
% Local function 1
function [out_11, ..., out_1n] = local1(in_11, ..., in_1m)
% Some statements
end
% Local function 2
function [out_21, ..., out_2n] = local2(in_21, ..., in_2m)
% Some statements
end
% More local functions ...
% Local function k
function [out_k1, ..., out_kn] = localk(in_k1, ..., in_km)
% Some statements
end
The main function is accessible from the outside of the file. The local functions are only accessible from within the file.
Each local function has its own workspace. Variables defined in other workspaces are not visible inside the function body. Similarly, variables defined in a local function body are not accessible from the outside of the function. Once the execution of a local function has finished, all variables in the function body are cleared immediately.